//
//  BDMSwitch.m
//  imanager
//
//  Created by liyingpeng on 15/10/29.
//  Copyright © 2015年 liyingpeng. All rights reserved.
//

#import "BDMSwitch.h"

static NSMutableDictionary *_groupSwitchDic = nil;

@implementation BDMSwitch

+ (NSMutableArray *)allSwitchButtonsForGroupId:(NSString *)groupId {
    NSMutableArray *gButtons = [_groupSwitchDic objectForKey:groupId];
    if (!gButtons) {
        gButtons = [NSMutableArray array];
    }
    
    return gButtons;
}

- (id)initWithGroupId:(NSString*)groupId {
    self = [super init];
    if (self) {
        _groupId = [groupId copy];
        
        [self addToGroup];
        
        self.exclusiveTouch = YES;
    }
    return self;
}

- (void)dealloc {
    [self removeFromGroup];
}

- (void)addToGroup {
    if(!_groupSwitchDic){
        _groupSwitchDic = [[NSMutableDictionary alloc] init];
    }
    
    NSMutableArray *gButtons = [_groupSwitchDic objectForKey:_groupId];
    if (!gButtons) {
        gButtons = [NSMutableArray array];
    }
    [gButtons addObject:self];
    [_groupSwitchDic setObject:gButtons forKey:_groupId];
}

- (void)removeFromGroup {
    if (_groupSwitchDic) {
        NSMutableArray *gButtons = [_groupSwitchDic objectForKey:_groupId];
        if (gButtons) {
            [gButtons removeObject:self];
            if (gButtons.count == 0) {
                [_groupSwitchDic removeObjectForKey:_groupId];
            }
        }
    }
}

- (void)unSelectOtherButtons {
    NSMutableArray *gButtons = [_groupSwitchDic objectForKey:_groupId];
    if (gButtons.count > 0) {
        for (UISwitch *button in gButtons) {
            if (button.isOn && ![button isEqual:self]) {
                [button setOn:NO animated:YES];
            }
        }
    }
}

- (void)setOn:(BOOL)on {
    if (on) {
        [self unSelectOtherButtons];
    }
    
    [super setOn:on];
}

- (void)setOn:(BOOL)on animated:(BOOL)animated {
    if (on) {
        [self unSelectOtherButtons];
    }
    
    [super setOn:on animated:animated];
}

@end
